package com.drojian.demo4.internet;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class GsonJsonActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn1;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part4_activity_gson_json);
        btn1 = findViewById(R.id.btn1);
        textView = findViewById(R.id.gson_View);
        btn1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:{
                try {
                    parseGson();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
            }
        }
    }

    private void parseGson() throws Exception {
        InputStream file = getAssets().open("data1.json");
        BufferedReader reader = new BufferedReader(new InputStreamReader(file));
        StringBuilder jsonString = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonString.append(line);
        }
        reader.close();

        Gson gson = new Gson();
        List<Person> people = gson.fromJson(jsonString.toString(), new TypeToken<List<Person>>(){}.getType());
        StringBuilder builder = new StringBuilder();

        for (Person user:people){
            String aa = user.toString();
            builder.append(aa+"\n");

        }
        textView.setText(builder);

    }
}

